package com.seewo.dubbo.debugger.admin.common.validate;

import com.seewo.dubbo.debugger.admin.common.validate.group.Group;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author chenliangliang
 * @date 2018/8/2
 */
public class ValidatorUtil {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws IllegalArgumentException 校验不通过，则报RRException异常
     */
    @SafeVarargs
    public static void validate(Object object, Class<? extends Group>... groups)
            throws IllegalArgumentException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new IllegalArgumentException(constraint.getMessage());
        }
    }

}
